<script lang="ts" setup>
import { getPatientConsultOrderListAPI } from '@/api/consult'
import { DeletePatientOrderAPI, PutCancelPatientOrderAPI } from '@/api/order'
import {
  OrderStatus,
  type GetPatientConsultOrderListParams,
  type GetPatientConsultOrderListRes,
} from '@/types/consult'
import { onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'

// 获取订单参数
const props = defineProps<{
  type: number
}>()

const orderParams = ref<GetPatientConsultOrderListParams>({
  current: 1,
  pageSize: 10,
  type: props.type,
})
// 订单列表
const orderList = ref<GetPatientConsultOrderListRes[]>([])

// 总页数
const pageTotal = ref(0)

// 加载状态
const loadMoreStatus = ref<UniHelper.UniLoadMoreStatus>('loading')

// 获取订单列表
const getOrderList = async (isMore = false) => {
  // 设置加载状态
  loadMoreStatus.value = 'loading'
  try {
    const res = await getPatientConsultOrderListAPI(orderParams.value)
    // 如果是加载更多，则拼接数据
    orderList.value = isMore ? [...orderList.value, ...res.rows] : res.rows
    pageTotal.value = res.pageTotal

    // 判断是否还有更多数据,设置加载状态
    if (orderParams.value.current! < pageTotal.value) {
      loadMoreStatus.value = 'more'
    } else {
      loadMoreStatus.value = 'noMore'
    }
  } catch (error) {
    loadMoreStatus.value = 'more'
  }
}

// 下拉刷新状态
const refresherTriggered = ref(false)

// 下拉刷新
const onRefresh = async () => {
  refresherTriggered.value = true
  orderParams.value.current = 1
  await getOrderList()
  refresherTriggered.value = false
}

// 加载更多
const loadMore = () => {
  if (orderParams.value.current! >= pageTotal.value) return
  orderParams.value.current!++
  getOrderList(true)
}

getOrderList()

// 在组件中定义状态与类名的映射关系
const statusClassMap = {
  [OrderStatus.待支付]: 'color-1',
  [OrderStatus.待接诊]: 'color-2',
  [OrderStatus.咨询中]: 'color-2',
  [OrderStatus.已完成]: 'color-3',
  [OrderStatus.已取消]: 'color-3',
}

// 更多按钮的显示状态
const activeShowMoreId = ref('')

// 页面显示
onShow(() => {
  orderParams.value.current = 1
  getOrderList()
})

// 删除订单
const handleDeleteOrder = async (id: string) => {
  console.log('删除订单', id)
  await DeletePatientOrderAPI(id)
  uni.showToast({
    title: '删除成功',
    icon: 'success',
  })
  orderList.value = orderList.value.filter((item) => item.id !== id)
}

// 继续咨询
const handleContinueConsult = (id: string) => {
  console.log('继续咨询', id)
  uni.navigateTo({
    url: `/subpkg_consult/room/room?orderId=${id}`,
  })
}

// 咨询其它医生
const handleConsultOtherDoctor = () => {
  uni.switchTab({
    url: '/pages/index/index',
  })
}

// 取消订单
const handleCancelOrder = async (id: string) => {
  console.log('取消订单', id)
  await PutCancelPatientOrderAPI(id)
  uni.showToast({
    title: '取消成功',
    icon: 'success',
  })
  orderList.value.find((item) => item.id === id)!.status = OrderStatus.已取消
}

// 去支付
const handlePayOrder = (id: string) => {
  console.log('去支付', id)
  uni.navigateTo({
    url: `/subpkg_consult/order_detail/order_detail?orderId=${id}`,
  })
}
</script>

<template>
  <scroll-view
    refresher-enabled
    refresher-background="#f6f6f6"
    class="uni-scroll-view"
    scroll-y
    @click="activeShowMoreId = ''"
    @scrolltolower="loadMore"
    @refresherrefresh="onRefresh"
    :refresher-triggered="refresherTriggered"
  >
    <view class="consult-list">
      <view class="consult-list-item" v-for="item in orderList" :key="item.id">
        <view class="consult-header">
          <view class="label">
            <image class="doctor-avatar" src="/static/uploads/doctor-avatar.jpg" />
            <text>{{ item.typeValue }}（自动分配医生）</text>
          </view>
          <text class="status" :class="statusClassMap[item.status]">{{ item.statusValue }}</text>
        </view>
        <navigator
          class="consult-body"
          hover-class="none"
          :url="`/subpkg_consult/order_detail/order_detail?orderId=${item.id}`"
        >
          <uni-list :border="false">
            <uni-list-item :border="false" title="病情描述" :right-text="item.illnessDesc" />
            <uni-list-item :border="false" title="价格" :right-text="item.payment.toString()" />
            <uni-list-item :border="false" title="创建时间" :right-text="item.createTime" />
          </uni-list>
        </navigator>
        <view class="consult-footer">
          <view class="uni-button more" v-if="item.status === OrderStatus.已完成">
            <text
              class="label"
              @click.stop="activeShowMoreId = activeShowMoreId === item.id ? '' : item.id"
              >更多</text
            >
            <uni-transition :show="activeShowMoreId === item.id">
              <view class="list">
                <view class="list-item">查看处方</view>
                <view class="list-item" @click="handleDeleteOrder(item.id)">删除订单</view>
              </view>
            </uni-transition>
          </view>
          <template v-if="item.status === OrderStatus.待支付">
            <button class="uni-button minor" @click="handleCancelOrder(item.id)">取消订单</button>
            <button class="uni-button" @click="handlePayOrder(item.id)">去支付</button>
          </template>

          <template v-if="item.status === OrderStatus.待接诊">
            <button class="uni-button minor" @click="handleCancelOrder(item.id)">取消订单</button>
            <button class="uni-button" @click="handleContinueConsult(item.id)">继续咨询</button>
          </template>

          <template v-if="item.status === OrderStatus.咨询中">
            <button class="uni-button" @click="handleContinueConsult(item.id)">继续咨询</button>
          </template>

          <template v-if="item.status === OrderStatus.已完成">
            <button class="uni-button minor" @click="handleContinueConsult(item.id)">
              问诊记录
            </button>
            <button v-if="item.evaluateId" class="uni-button minor">查看评价</button>
            <button v-else class="uni-button">去评价</button>
          </template>

          <template v-if="item.status === OrderStatus.已取消">
            <button class="uni-button minor" @click="handleDeleteOrder(item.id)">删除订单</button>
            <!-- 咨询其它医生就是跳转到首页 -->
            <button class="uni-button" @click="handleConsultOtherDoctor">咨询其它医生</button>
          </template>
        </view>
      </view>

      <!-- 加载状态 -->
      <uni-load-more
        :status="loadMoreStatus"
        color="#C3C3C5"
        :icon-size="16"
        :content-text="{
          contentdown: '上拉显示更多',
          contentrefresh: '数据正在加载中',
          contentnomore: '没有更多数据了',
        }"
      />
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import './styles.scss';
</style>
